import React, { useState, useRef, useEffect } from 'react';
import { Form, Tabs, Row, Col, Button, message } from 'antd';
import DefineInterface from './DefineInterface';
import DefineReturn from './DefineReturn';
import services from '../../../../../services/api';
import { flattenDepth } from 'lodash';
import '../index.less';
import { connect } from 'react-redux';

const InterfaceManageAdd = (props) => {
  const { form } = props;
  const [activeKey, setActiveKey] = useState('0');
  const [value, setValue] = useState({});
  const [hasSet, setHasSet] = useState(false);
  const [curFaceId, setCurFaceId] = useState(null);
  const id = props.match.params.id;
  const defineInterfaceRef = useRef();
  const defineReturnRef = useRef();

  useEffect(() => {
    props.dispatch({ type: 'pageClose/waringAdd' });
    return () => props.dispatch({ type: 'pageClose/waringReduce' });
  })

  useEffect(() => {
    id && getInnerInterfaceDetail();
  }, []);

  // 获取计费配置json
  const getPriceJson = (priceJson) => {
    const temp = { ...value };
    temp['priceJson'] = priceJson;
    setValue(temp);
  };

  const getInnerInterfaceDetail = async () => {
    const { code, msg, data } = await services.interfaceManage.detail(id);
    if (code) return message.error(msg);
    const {
      successExample: tpSuccessExample,
      returningType: tpReturningType,
      supplierId,
      id: thirdInterfaceId,
    } = data.thirdInterfaceList[0];
    data.codeMaps.length && getCodeMap(data);
    data.thirdInterfaceList = [{ interfaceId: thirdInterfaceId }];
    setValue((prevState) => ({
      ...prevState,
      tpSuccessExample,
      tpReturningType,
      supplierId,
      thirdInterfaceId,
      ...data,
    }));
  };

  // 编辑时 构造codeMap
  const getCodeMap = (data) => {
    const { codeMaps, returningMaps } = data;
    const tempObj = {};
    codeMaps.forEach((item) => {
      if (!tempObj[item.srcKey]) {
        tempObj[item.srcKey] = [item];
      } else {
        tempObj[item.srcKey].push(item);
      }
    });
    returningMaps.forEach((item) => {
      item.codeMap = tempObj[item.thirdPath];
    });
  };

  const handleSubmit = () => {
    form.validateFields(async (errors, values) => {
      if (!errors) {
        const {
          thirdInterfaceList: [{ interfaceId: thirdInterfaceId }],
        } = value;
        const params = {
          dataSourceType: 0,
          ...value,
          ...values,
          ...defineInterfaceRef.current.getDiData(),
          ...defineReturnRef.current.getDrData(),
        };
        const { returningMaps } = params;
        // code映射集合
        const codeMapList = flattenDepth(
          returningMaps.filter((item) => !!item.codeMap).map((item) => item.codeMap)
        ).map((item) => {
          item['thirdInterfaceId'] = thirdInterfaceId;
          return item;
        });
        params['codeMaps'] = codeMapList;
        // 返回值映射集合
        try {
          returningMaps.forEach((item) => {
            for (const key in item) {
              if (item[key] === '') throw '请完善返回值映射！';
            }
            item['thirdInterfaceId'] = thirdInterfaceId;
            Reflect.deleteProperty(item, 'codeMap');
          });
        } catch (error) {
          return message.warning(error);
        }
        const { code, msg } = await services.interfaceManage[id ? 'update' : 'add']({ id, ...params });
        if (!code) {
          message.success('操作成功');
          props.history.push('/dataGateway/interfaceManage');
        } else {
          message.error(msg);
        }
      }
    });
  };

  const renderInterfaceNodes = () => (
    <div className='add_interface'>
      <DefineInterface
        {...props}
        handleDataSourceChange={handleDataSourceChange}
        value={value}
        ref={defineInterfaceRef}
        getPriceJson={getPriceJson}
      />
    </div>
  );

  const renderRuturnNodes = () => (
    <div className='add_interface'>
      <DefineReturn {...props} ref={defineReturnRef} value={value} curFaceId={curFaceId} />
    </div>
  );

  const handleDataSourceChange = (value) => {
    value && getParamsByThird(value);
    setCurFaceId(value)
  };

  // 根据选择的数据源渲染 入参 出参 映射
  const getParamsByThird = async (interfaceId) => {
    const thirdInterfaceList = [{ interfaceId }];
    const {
      data: { params, feeRules, successExample, returningType },
    } = await services.dataSource.detail(interfaceId);
    const enterParams = params
      .filter((item) => !item.val)
      .map((item) => {
        const { name, position, type, nonEmpty, id: paramId } = item;
        const tempObj = {
          thirdParamList: [{ ...item, interfaceId, paramId }],
          // 入参设置默认值
          name,
          position,
          type,
          nonEmpty,
        };
        return tempObj;
      });
    const constantParam = params.filter((item) => item.val);
    const thirdFeeRuleList = feeRules.map((item) => {
      return {
        ...item,
        interfaceId,
        feeRuleId: item.id,
      };
    });
    const newFeeRules = {
      name: '',
      code: '',
      feeRuleType: 1,
      thirdFeeRuleList,
    };
    const tempObj = {
      tpSuccessExample: successExample,
      tpReturningType: returningType,
      params: enterParams,
      tparams: constantParam,
      feeRules: [newFeeRules],
    };
    setValue({ ...value, ...tempObj, thirdInterfaceId: interfaceId, thirdInterfaceList });
  };

  const handleNext = () => {
    form.validateFields(
      ['name', 'flag', 'isRateLimit', 'rateMax', 'groupId', 'feeType', 'supplierId', 'thirdInterfaceId'],
      (error) => {
        if (!error) {
          setHasSet(true)
          setActiveKey('1')
          return
        }
      }
    );
  };

  return (
    <div className='add'>
      <Form>
        <Tabs style={{ width: '100%' }} activeKey={activeKey} onChange={setActiveKey}>
          <Tabs.TabPane tab={'定义接口'} key='0' forceRender={true}>
            {renderInterfaceNodes()}
          </Tabs.TabPane>
          {hasSet && (
            <Tabs.TabPane tab={'定义返回'} key='1' forceRender={true}>
              {renderRuturnNodes()}
            </Tabs.TabPane>
          )}
        </Tabs>
        <Row type='flex' justify='start' className='operate_button'>
          <Col>
            {activeKey === '1' ? (
              <Button type='primary' onClick={handleSubmit}>
                保存
              </Button>
            ) : (
              <Button type='primary' onClick={handleNext}>
                下一步
              </Button>
            )}
          </Col>
        </Row>
      </Form>
    </div>
  );
};
export default connect()(Form.create()(InterfaceManageAdd));
